package com.banmao.CarlCamp.Day02;

/**
 *  https://leetcode.cn/problems/minimum-size-subarray-sum/
 */
public class LC209 {

    public int minSubArrayLen2(int target, int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        // 滑动窗口?
        int left = 0, right = 1;
        int sum = nums[left];
        int len = (sum == target) ? 1 : Integer.MAX_VALUE;
        while (right <= nums.length) {
            if (sum == target) {
                len = Math.min((right - left), len);
                sum -= nums[left];
                left++;
            } else if (sum > target) {
                // 和超过，收紧窗口
                sum -= nums[left];
                left++;
            } else {
                // 和未满，伸展窗口
                if (right >= nums.length) {
                    break;
                }
                sum += nums[right];
                right++;
            }
        }
        return (len == Integer.MAX_VALUE) ? 0 : len;
    }

    // Carl的滑动窗口
    public int minSubArrayLen(int s, int[] nums) {
        int left = 0;
        int sum = 0;
        int result = Integer.MAX_VALUE;
        for (int right = 0; right < nums.length; right++) {
            sum += nums[right];
            while (sum >= s) {
                result = Math.min(result, right - left + 1);
                sum -= nums[left++];
            }
        }
        return result == Integer.MAX_VALUE ? 0 : result;
    }

    public static void main(String[] args) {
        LC209 lc209 = new LC209();

        int[] nums = {1,2,3,4,5};
        int len = lc209.minSubArrayLen(11, nums);
        System.out.println(len);
    }

}
